/**
 * Created by liubin on 2015/09/25.
 */
'use strict';

import { Map, List, fromJS } from 'immutable';
import { SELECT_USERLIST_PAGING, GET_USER, ADD_USER, MODIFY_USER, REMOVE_USER} from 'actions/userAction';
import { SUCCESS } from 'actions/baseAction';

const initialState = Map({
    userList: List(),
    user: Map()
});

export function userStore(state = 'DEFAULT', action = {type: 'DEFAULT'}) {
    switch (action.type) {
        case SELECT_USERLIST_PAGING:
            const data = action.data.map(value => {
                value.op = '';
                return value;
            });
            state = state.set('userList', List(action.data));
            if (action.callback) {
                action.callback({
                    draw: action.draw,
                    recordsTotal: action.total,
                    recordsFiltered: action.total,
                    data
                });
            }
            return state;
        case ADD_USER:
            if (action.status == SUCCESS ) {
                action.callback();
            }
            return state;
        case MODIFY_USER:
            const { d } = action;
            if (action.status == SUCCESS ) {
                const { data } = action;
                //const user = action.data;
                //const q = action.q;
                state = state.set('user', data);
                d.resolve();
            } else {
                const { message } = action;
                d.reject(message);
            }
            return state;
        case GET_USER:
            if (action.status == SUCCESS ) {
                const user = action.data;
                if (user) {
                    state = state.set('user', fromJS(user));
                    if (action.callback) {
                        // 延时回调
                        setTimeout(() => {
                            action.callback();
                        }, 500);
                    }
                }
            }
            return state;
        case REMOVE_USER:
            if (action.status == SUCCESS ) {
                action.callback();
            }
            return state;
        default:
            return state === 'DEFAULT' ? initialState : state;
    }

}